﻿namespace Mp3Observer.Common
{
    #region usings

    using System;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.Windows;

    #endregion

    public static class General
    {
        /// <summary>
        /// Shows the exception in a custom messagebox executed with a new process
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="value">The guid value.</param>
        // [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        // [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "its ok here because we show already the exception box ")]
        // [PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
        public static void ErrorBox(Exception exception, Guid value)
        {
            string errorMessage = String.Format(CultureInfo.InvariantCulture, "{0} in {1}: {2}", exception.GetType().ToString(), exception.Source, exception.Message);
            string stackTrace = exception.StackTrace;
            Exception innerException = exception;
            while (innerException != null)
            {
                errorMessage = String.Format(CultureInfo.InvariantCulture, "{0}: {1}", innerException.Source, innerException.Message);
                stackTrace = innerException.StackTrace;
                innerException = innerException.InnerException;
            }

            string myLocalAppPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName; // Xenon.Common.Miscellaneous.Storage.LocalApplicationDataFolder;
            FileStream fs = new FileStream(myLocalAppPath + "\\" + value.ToString() + ".txt", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(errorMessage.ToString());
            sw.WriteLine(stackTrace.ToString());
            sw.Flush();
            sw.Close();
            fs.Close();

            // Start ErrorBox.exe for the ErrorBox
            ProcessStartInfo startInfo = new ProcessStartInfo("ErrorBox.exe", value.ToString());
            try
            {
                Process.Start(startInfo);
            }
            catch (Exception)
            {
                MessageBox.Show(errorMessage + "\n\n" + stackTrace, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
